package thread;

//通过懒汉模式构造单例模式

//多线程版
class SingletonLazy{
    private static volatile SingletonLazy instance = null;//预防内存可见性问题
    //volite的功能： 确保每次读取操作都是读内存  关于该变量的读取和修改操作不会触发重排序
    //private static SingletonLazy instance = null;
    private static Object locker = new Object();

    private SingletonLazy(){

    }

    public static SingletonLazy getInstance(){//优化
        if (instance == null){//这个if是判断是否需要加锁
            synchronized (locker){
                if (instance == null){//这个if是判断是否需要new 对象
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    public static SingletonLazy getInstance3(){

            synchronized (locker){//当把实例创建好后，后续再调用getInstance，此时都是直接执行return
                if (instance == null){//但是，每次调用上述的方法，都会触发一次加锁操作，虽然不涉及线性安全问题
                    instance = new SingletonLazy();//多线程情况下，这里的加锁就会相互阻塞，影响程序运行效率
                }
            }

        return instance;
    }

    public static SingletonLazy getInstance2(){
        if (instance == null){
            synchronized (locker){

                instance = new SingletonLazy();

            }
        }
        return instance;
    }

    public synchronized static SingletonLazy getInstance1(){
        if (instance == null){
            instance = new SingletonLazy();
        }
        return instance;
    }
}


//单线程版
//class SingletonLazy{
//    private static SingletonLazy instance = null;
//
//    private SingletonLazy(){
//
//    }
//
//    public static SingletonLazy getInstance(){
//        if (instance == null){
//            instance = new SingletonLazy();
//        }
//        return instance;
//    }
//}

public class Demo29 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);

        // SingletonLazy s3 = new SingletonLazy();
    }
}
